"use strict";
/**
 * 猜大小 2
 * http://gameapp.wanlitong.com/?act=guess
 */
!function ($, global) {

    var LightboxV2 = PA.ui.LightboxV2;
    var Client = Client || {};

    var touchStart = 'mousedown',
        touchEnd = 'mouseup',
        Click = 'click';
    if ('ontouchend' in document) {
        touchStart = 'touchstart';
        touchEnd = 'touchend';
        Click = 'tap';
    }
    var MSG = {
        timeout: '网络超时啦'
    }

    global.Guess = {
        /**
         *
         */
        Conf: {
            ajaxSettings: {
                timeout: 20000
            },
            audioPath: GM.cdnPath + "audio/game/guess2/",
            imagePath: GM.cdnPath + "images/game/guess2/",
            gameId: "",
            userId: null,
            appId: null,
            loginUrl: '?act=user&st=login',
            url_login_wlt: 'native://login',
            url_pay_wlt: '?act=recharge'
        },

        /**
         *
         */
        Model: {
            progressSts: 0,
            isNewUser: false,
            userNoticed: false,
            prizeAmountTotal: 0,
            gameScore: 0,
            tCoin: 0,
            total: 0,
            bet: 100,
            defaultScore: 100,
            checkLogin: false,
            guesstype: null,//small
            boult: [1, 1, 1],
            prizeAmount: null,
            rechargeType: 2,
            prizeType: 2,
            gameCoin: 0,
            daoju: 0,
            payback: { code: null, betPoint: null, paybackPoint: null },
            betPoint2: 0,
            paybackPoint2: 0,
            resultready: false,
            currentPool: 0,
            gamestart: false,
            isLose: null,
            isUseEn: null
        },
        View: {},
        /**
         * 状态
         */
        Status: {
            isNewUser: false,
            gameRunning: false
        },
        data: {
            msg: '',
            useBaoxian: 0,  // 是否使用了保险， 0 代表没有使用保险, 1代表使用了保险
            errorcode: false
        },
        res: {
            boxSprite: {
                image: null,
                'ball1': { width: 149, height: 149, x: 30, y: 30 },
                'ball2': { width: 149, height: 149, x: 315, y: 30 },
                'ball3': { width: 149, height: 149, x: 30, y: 250 },
                'ball4': { width: 149, height: 149, x: 315, y: 250 },
                'ball5': { width: 149, height: 149, x: 30, y: 480 },
                'ball6': { width: 149, height: 149, x: 315, y: 480 },
                'ballShadow': { width: 149, height: 149, x: 40, y: 700 },
                'dragonHeadTop': { width: 360, height: 301, x: 70, y: 930 },
                'dragonHeadBottom': { width: 422, height: 155, x: 40, y: 1330 },
                'dragonEyeLeft': { width: 40, height: 35, x: 283, y: 753 },
                'dragonEyeRight': { width: 40, height: 35, x: 444, y: 753 },
                'star': { width: 16, height: 14, x: 292, y: 693 },
                'src': GM.cdnPath + 'images/game/guess2/dragonballs/boxSprite.png'
                // 'src': 'images/boxSprite.png'
            },
            lightSprite: {
                image: null,
                'src': GM.cdnPath + 'images/game/guess2/dragonballs/light.png'
                // 'src': 'images/light.png'
            },
            txtSprite: {
                image: null,
                'lose': { width: 262, height: 250, x: 5, y: 10 },
                'win': { width: 260, height: 297, x: 6, y: 290 },
                'src': GM.cdnPath + 'images/game/guess2/dragonballs/txtSprite.png'
                // 'src': 'images/txtSprite.png'
            }
        },
        initParam: function () {
            var self = this;
            self.View = {
                LB_paInsure: new LightboxV2({
                    target: $("#paInsure"),
                    clickMask: false
                }).hookHidden(function () {
                    if (self.Model.isUseEn !== true) {
                        self.socketExec();
                    }
                    self.Model.isUseEn = null;
                }),
                // LB_load : new LightboxV2({ target:$("#loadreg"), clickMask:false }),
                LB_rechargePopup: new LightboxV2({ target: $("#rechargePopup") }),
                LB_tips: new LightboxV2({
                    target: $("#tips")
                }),
                LB_funTips: new LightboxV2({ target: $("#funTips") }),
                $winTxtCont: $('.winTxtCont'),
                $loseTxtCont: $('.loseTxtCont')
            };
        },
        getUserAccount: function () {
            var self = this;
            if (window.GM && GM.getUserAccount) {
                GM.getUserAccount(function (d) {
                    self.Model.gameScore = d.gameScore;
                    self.Model.tCoin = d.TCoin;
                });
            }
        },
        socketExec: function () {
            var self = this;
            if (!self.Model.isLose) {
                self.Model.isLose = null;
                return;
            }
            self.Model.isLose = null;
            if (window.GM && GM.socket_RJ) {
                if (GM.socket_RJ.exec) {
                    GM.socket_RJ.exec();
                }
                var getMoney = GM.socket_RJ.getMoney;
                if (getMoney && getMoney() > 0) {
                    self.getUserAccount(); // 重新更新 余和币
                }
            }

        },
        /**
         * DOM init
         */
        initCom: function () {
            var self = this;

            var $betVal = $('#betCtrl input');

            !function () {
                $('#funTips .buttom-wrap .gs-ui').on(touchEnd, function () {
                    var _LB_rechargePopup = self.View.LB_rechargePopup || new LightboxV2({ target: $("#rechargePopup") });
                    _LB_rechargePopup.show();
                });
            }();

            !function () {
                $('#guessCon > canvas').on(touchEnd, function () {
                    $betVal.blur();
                });
            }();

            //betInput
            var inputVal = function (f) {
                $('#betCtrl .btn-subtract').on(touchStart, function () {
                    $('.sp-subtract').addClass('active');
                }).on(touchEnd, function () {
                    $('.sp-subtract').removeClass('active');
                });

                $('#betCtrl .btn-add').on(touchStart, function () {
                    $('.sp-add').addClass('active');
                }).on(touchEnd, function () {
                    $('.sp-add').removeClass('active');
                });

                $('#betCtrl button').on(GM.touchEnd, function () {
                    if (self.Model.gamestart) {
                        return
                    } else if (!self.Model.checkLogin) {
                        location.href = self.Conf.loginUrl;
                        return
                    }
                    var _btnType = $(this).attr("data-type");
                    var _betVal = parseInt($betVal.val());

                    self.data.audiobtn.start();

                    var _step = 100;
                    if (_btnType === "btn-max") {
                        _betVal = self.Model.tCoin > self.Model.gameScore ? self.Model.tCoin : self.Model.gameScore;
                    }
                    if (_betVal < 10000) {
                        _step = 100
                    } else if (_betVal < 100000) {
                        _step = 5000
                    } else {
                        _step = 10000
                    }
                    switch (_btnType) {
                        case "btn-max":
                            _betVal = _betVal - _betVal % _step;
                            _betVal = _betVal < 500000 ? _betVal : 500000;
                            break;
                        case "btn-subtract":
                            if (_betVal >= 200)
                                _betVal -= _step;
                            break;
                        case "btn-add":
                            if (_betVal <= 499900)
                                _betVal += _step;
                            break;
                    }


                    $betVal.val(_betVal);
                });

                $betVal.focus(function (e) {
                    if (self.Model.gamestart) {
                        $betVal.blur();
                        return
                    }
                    $('.bet-choose').show();
                });

                /*$('body').on(GM.touchStart, function(e){
                  console.log(e.target)
                });*/
                //快速投币选择 betChoose  #betCtrl > span > div > ul > li:nth-child(1)
                $('#betCtrl .bet-pan .bet-choose').on(GM.touchEnd, 'li', function (event) {//
                    var _this = event.target;
                    var _val = $(_this).attr('data-value');
                    if (!_val) return;
                    $betVal.val(_val);
                    $('#betCtrl input').blur();
                    // $('.bet-choose').hide();
                })
                //输入框
                $betVal.keyup(function (e) {
                    var val = parseInt($(this).val());
                    if (isNaN(val)) {
                        // val = 100;
                    } else if (val >= 500000) {
                        val = 500000;
                        $(this).val(val);
                    }

                }).blur(function (e) {
                    if ($(this).val() <= 100 || isNaN($(this).val())) {
                        $(this).val("100");
                    }
                    var value = $(this).val() - $(this).val() % 100;
                    $(this).val(value);

                    // setTimeout(function(){
                    $('.bet-choose').fadeOut(310);
                    // }, 110);

                }).change(function () {
                    var $value = $(this).val();
                    if (isNaN($value)) {
                        $value = 100;
                    }
                    else {
                        if ($value <= "") {
                            $value = "";
                        }
                        else if ($value > 500000) {
                            $value = 500000;
                        }
                    }
                    $(this).val($value);
                });
            }(false);
            //充值
            var regchargePoup = function (f) {
                var LB_rechargePopup = new LightboxV2({ target: $("#rechargePopup") });
                //监听键盘输入
                var keydownLimit = function (e) {
                    var keyCode = e.keyCode;
                    var str = String.fromCharCode(keyCode);
                    if (!regNum.test(str) && keyCode !== 8) {
                        e.preventDefault();
                    }
                };

                $('div.purse  button.recharge, .indicate button.icon-recha').on(GM.touchEnd, function () {
                    if (!self.Model.checkLogin) {
                        location.href = self.Conf.loginUrl;
                        return
                    }
                    LB_rechargePopup.show();
                });
                var $tInput = $('#rechargePopup input');

                $tInput.on('keydown', keydownLimit)
                    .on('keyup', function () {
                        $('#rechargePopup .m-choose li.select').removeClass('select');
                    });

                $('#rechargePopup .m-choose li').on(GM.touchEnd, function () {
                    $(this).siblings('.select').removeClass('select');
                    $(this).addClass('select');
                    $tInput.val(parseInt($(this).attr('data-val')));
                });
                $('#rechargePopup div.bottom-warp button').on(GM.touchEnd, function () {
                    var checkInteger = (function () {
                        var reg = /^[1-9]\d*$/;
                        return function (val) {
                            var valid = !isNaN(val) && reg.test(val);
                            return valid;
                        }
                    })();
                    var money = $('#rechargePopup .gs-ui.m-input input[type="tel"]').val();
                    if (!checkInteger(money)) {
                        self.popbox('充值金额必须是正整数');
                        return false;
                    }

                    self.redirectPay(money);
                });
            }(false);
            //帮助，新手引导
            var userGuidePoup = function (f) {
                var LB_userGuidePoup = new LightboxV2({
                    target: $(".game-rule")
                });
                $('button.icon-help').on(GM.touchEnd, function () {
                    LB_userGuidePoup.show()
                });
            }(false);
            //排行榜,
            /*var topList = function(f){
              var LB_toplistPoup = new LightboxV2({
                      target: $("#toplistPoup")
                  });
              self.topList(0);
              $('button.icon-award').on(GM.touchEnd, function(){
                  LB_toplistPoup.show();
                });
            }(false);*/
            //投币
            var betPlay = function (f) {
                var $gsCtrl = $('#gsCtrl');
                $gsCtrl.children('a').touchendV1(function () {
                    if (self.Model.gamestart) return;
                    $('#betCtrl input').blur();

                    var $window = $(window);
                    var $marquee3 = $('.marquee3');
                    var _hfheight = $marquee3.height() / 2;
                    if ($window.scrollTop() < _hfheight) {
                        GM.scrollAni(_hfheight + 2);
                    }
                    // 龙bite 音效 + 动画效果
                    self.Game.start();

                    self.Model.deg = 90;
                    self.Model.speed = 0.5;

                    $(this).addClass('active');
                    self.data.audioclick.play();
                    var _type = $(this).attr('data-type');

                    self.play(_type);
                });
            }(false);
            //voice switch
            var iconVoice = function (f) {
                var $iconVoice = $('#indicate .icon-voice');
                $iconVoice.on(GM.touchEnd, function () {
                    if ($(this).hasClass("horn-forb")) {
                        $(this).removeClass("horn-forb");
                        self.data.audiobg.play();
                    } else {
                        $(this).addClass("horn-forb");
                        self.data.audiobg.pause();
                    }
                });
            }(false);
            !function () {
                $('.icon-award').on(GM.touchEnd, function () {
                    /*if(!self.Model.checkLogin){
                      location.href = self.Conf.loginUrl;
                    }else{*/
                    location.href = "?act=game_rolldice2&st=fuhaobang"
                    // }
                });

                $('button.gs-icon.tuhao').touchendV1(function () {
                    location.href = "?act=game_rolldice2&st=bet_rank";
                });
            }();

            //跑马灯
            var marqueeList = function (f) {
                self.getAnnounce();

                setInterval(function () {
                    self.getAnnounce();
                }, 5 * 60 * 1000);

                var $window = $(window);

                $window.scroll(function () {
                    if ($window.scrollTop() > $('.marquee3').height() / 2) {
                        $('.marquee3').hide();
                    } else {
                        $('.marquee3').show();
                    }
                })


            }(false);
            //平安娱乐险
            !function () {
                var confirm = 'Y';
                var $paInsure = $("#paInsure");
                var LB_paInsure = self.View.LB_paInsure;
                $('#paInsure .use-it').on(GM.touchEnd, function () {
                    var daojuCode = self.Model.payback.code;
                    self.data.useBaoxian = 1;
                    self.Model.isUseEn = true;
                    $.ajax({
                        type: "get",
                        url: "?act=game_rolldice2&st=use_prop",
                        data: { "confirm": confirm, "code": daojuCode },
                        timeout: 10000,
                        success: function (d) {
                            var rsp = typeof d === 'string' ? $.parseJSON(d) : d;
                            if (rsp.statusCode == '0000') {
                                // self.popbox 会调用self.View.LB_tips
                                self.View.LB_tips.hookHiddenOnce(function () {
                                    self.socketExec();
                                });
                                //结算
                                self.popbox('平安娱乐险成功为您避免了' + rsp.paybackPoint + '损失');
                                self.userAccount();
                            } else if (rsp.statusCode == '3') {
                                self.popbox('抱歉，余额不足，请充值后继续');
                                self.userAccount();
                            } else {
                                self.popbox('手慢了，道具已过期~');
                                self.userAccount();
                            }

                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            // 超时也触发倒霉险
                            self.View.LB_tips.hookHiddenOnce(function () {
                                self.socketExec();
                            });
                            if (textStatus == "timeout") {
                                self.popbox('网络超时啦');
                            } else {
                                self.popbox('哎~网络出错啦！');
                            }
                        }
                    });
                });

                /*LB_paInsure.hookHiding(function(){
                  var confirm, daojuCode;
          
                  if( self.data.useBaoxian === 0 ){
                    confirm = 'N';
                    daojuCode = self.Model.payback.code;
          
                    $.ajax({
                      type:"post",
                      url : "?act=game_rolldice2&st=use_prop",
                      data:{
                        "confirm": confirm,
                        "code": daojuCode
                      }
                    });
                  }
                  // 重置这个 value
                  self.data.useBaoxian = 0;
                });*/
            }();

            // 小屏
            !function () {
                GM.scrollAni = function (top, callback) {
                    var $window = $(window);
                    var done = function () {
                        if (typeof callback === 'function') {
                            callback();
                        }
                    }
                    var scrollTop = $window.scrollTop();
                    var diffTop = top - scrollTop;
                    var num = 12;
                    var topChange;
                    if (diffTop === 0) { // 直接执行 done
                        done();
                        return;
                    } else { // 高度大于当前的高度
                        if (diffTop < 0) {
                            num = -num;
                        }
                        topChange = function () {
                            scrollTop = scrollTop + num;
                            var diff = top - scrollTop;
                            if (diffTop < 0) {
                                diff = -diff;
                            }
                            if (diff > 0) {
                                return false;
                            } else {
                                if (diff < 0) {
                                    scrollTop = top;
                                }
                                return true;
                            }
                        }
                    }

                    var loop = function () {
                        var flag = topChange();
                        $window.scrollTop(scrollTop);
                        if (flag) {
                            done();
                            return;
                        }
                        setTimeout(loop, 25);
                    }
                    loop();
                }

                setTimeout(function () {
                    GM.scrollAni($(".purse").offset().top);
                }, 100)

            }();
        },
        /**
         * new yindao
         */
        userGuide: function () {
            var self = this;
            var LB_userGuidePoup = new LightboxV2({
                target: $(".game-rule")
            });
            //ajax
            if (self.Status.isNewUser) {
                LB_userGuidePoup.show()
            }
        },
        init: function () {
            var self = this;
            // 定义观察者模式, 查看色盅什么时候抬起

            self.initParam();
            self.setIncoming();//1029
            try {
                self.audioInit();
                self.data.audiobg.play();
                $(document).one(GM.touchEnd, function () {
                    // fix bug app audio play
                    self.audioInit();
                });
            } catch (e) {
                console.log(e)
            }
            self.imagesLoader(function () {

                self.checkLogin(function () {
                    self.initCom();
                    // self.userGuide();
                    self.userAccount(function () {

                    });
                });

                setTimeout(function () {
                    self.initCanvas();
                    self.reSizecanvas();
                    self.initStage();
                    progressbar(100, 0.6);//进度完成
                    self.Model.progressSts = true;
                }, 0)

            });
        },
        initCanvas: function () {
            var canvas = document.createElement("canvas");
            $('#guessCon').append(canvas);
            this.canvas = canvas;
            this.context = this.canvas.getContext("2d");
        },
        imagesLoader: function (callback) {
            var _this = this;
            this.load = function (src, callback) {
                var queue = new createjs.LoadQueue(true, null, true);
                queue.on("fileload", function (event) {
                    var type = event.item.type;
                    if (type == createjs.LoadQueue.IMAGE) {

                        //make a CreateJS Bitmap object from the result
                        callback(event.result);
                    }
                }, null, true);
                //create a LoadItem and set the crossOrigin property

                var loadItem = new createjs.LoadItem().set({
                    src: src,
                    crossOrigin: "Anonymous"
                });
                //load it
                queue.loadFile(loadItem);
            };
            this.init = function () {
                var self = this,
                    i = 0,
                    n = Object.keys(_this.res).length;
                $.each(_this.res, function (name, obj) {
                    self.load(obj.src, function (imgdata) {
                        obj.image = imgdata;
                        i++;
                        if (i === n) {
                            self.loaded = true;
                            callback();
                        }
                    });
                });
            };
            this.init();
        },
        reSizecanvas: function () {
            var _height = $('#guessCon').height(),
                _width = $('#guessCon').width();
            this.canvas.height = 890;
            this.canvas.width = 750;
        },
        initStage: function () {
            var self = this;
            var _stage = new createjs.Stage(self.canvas);
            this.stage = _stage;
            this.stage.scaleX = this.ratio;
            this.stage.scaleY = this.ratio;
            createjs.Ticker.setFPS(60);
            createjs.Ticker.addEventListener('tick', self.stage)
            self.initGame();
        },
        /**
         *
        */
        initGame: function () {

            var _this = this;
            var cw = _this.canvas.width;
            var ch = _this.canvas.height;

            var Tools = {
                createSprite: function (imgName, spriteName) {
                    var sprite = new createjs.Bitmap(_this.res[imgName].image);
                    if (spriteName) {
                        sprite.sourceRect = _this.res[imgName][spriteName];
                    }
                    return sprite;
                },
                setCenter: function (ele) {
                    var parent = ele.parent && ele.parent.canvas;
                    var pw = parent.width || parent.getBounds().width;
                    var iw = ele.width || ele.getBounds().width;
                    ele.x = (pw - iw) / 2;
                }
            };

            function createDragon(config) {
                this.config = config;
            }
            createDragon.prototype = {
                init: function () {
                    var self = this;
                    self.initConfig();

                    self.stage = _this.stage;
                    self.GameBox = new createjs.Container();
                    self.GameBox.y = self.config.gameBoxBounds.y;
                    self.stage.addChild(self.GameBox);
                    self.initLight();
                    self.initDragon();
                    self.showDragon();
                    self.initEye();
                },
                initDragon: function () {
                    var self = this;
                    var DragonHead = new createjs.Container();
                    var _dragonHeadBounds = self.config.dragonHeadBounds;
                    var _dragonHeadTopBounds = _dragonHeadBounds.topBounds;
                    var _dragonHeadBottomBounds = _dragonHeadBounds.bottomBounds;

                    self.DragonHead = DragonHead;

                    var dragonHeadTop = Tools.createSprite('boxSprite', 'dragonHeadTop');
                    dragonHeadTop.y = _dragonHeadTopBounds.y;
                    dragonHeadTop.x = (_dragonHeadBounds.width - _dragonHeadTopBounds.width) / 2;
                    self.dragonHeadTop = dragonHeadTop;

                    var dragonHeadBottom = Tools.createSprite('boxSprite', 'dragonHeadBottom');
                    dragonHeadBottom.x = _dragonHeadBottomBounds.x;
                    dragonHeadBottom.y = _dragonHeadBottomBounds.y;
                    self.dragonHeadBottom = dragonHeadBottom;

                    DragonHead.addChild(dragonHeadBottom);
                    DragonHead.addChild(dragonHeadTop);
                    self.dragonHeadTop = dragonHeadTop;

                    DragonHead.alpha = _dragonHeadBounds.hideStatus.alpha;
                    DragonHead.scaleX = DragonHead.scaleY = _dragonHeadBounds.hideStatus.scale;
                    DragonHead.regX = _dragonHeadBounds.width / 2;
                    DragonHead.regY = _dragonHeadBounds.height / 2;
                    DragonHead.x = cw / 2;
                    DragonHead.y = _dragonHeadBounds.height / 2;

                    self.GameBox.addChild(DragonHead);
                },
                showDragon: function (time) {
                    var self = this;
                    var _dragonHeadBounds = self.config.dragonHeadBounds;
                    createjs.Tween.get(self.DragonHead, {
                        override: true
                    }).to({
                        alpha: _dragonHeadBounds.showStatus.alpha,
                        scaleX: _dragonHeadBounds.showStatus.scale,
                        scaleY: _dragonHeadBounds.showStatus.scale
                    }, time || _dragonHeadBounds.showTime, createjs.Ease.quartOut);
                },
                openMouth: function (time, callback) {
                    var self = this;
                    var mouseData = self.config.dragonMouse;
                    var y = mouseData.range[1];

                    mouseData.status = 'open';
                    createjs.Tween.get(self.dragonHeadBottom, {
                        override: true
                    }).to({
                        y: y
                    }, time || mouseData.openTime, createjs.Ease.quartOut).call(function () {
                        if (callback && typeof (callback) == 'function') {
                            callback();
                        }
                    });
                },
                closeMouth: function (time, callback) {
                    var self = this;
                    var mouseData = self.config.dragonMouse;
                    var y = mouseData.range[0];

                    mouseData.status = 'close';
                    createjs.Tween.get(self.dragonHeadBottom, {
                        override: true
                    }).to({
                        y: y
                    }, time || mouseData.closeTime, createjs.Ease.quartOut).call(function () {
                        if (callback && typeof (callback) == 'function') {
                            callback();
                        }
                    });
                },
                bite: function (time) {
                    var self = this;
                    var mouseData = self.config.dragonMouse;
                    var y = mouseData.range[1];

                    mouseData.status = 'bite';

                    function bite() {
                        if (mouseData.status != 'bite') {
                            return;
                        }
                        createjs.Tween.get(self.dragonHeadBottom, {
                            override: true
                        }).to({
                            y: y
                        }, time || mouseData.biteTime, createjs.Ease.quartOut).call(function () {
                            if (y == mouseData.range[0]) {
                                y = mouseData.range[1];
                            } else {
                                y = mouseData.range[0];
                            }
                            setTimeout(bite, mouseData.biteWaiteTime);
                        });
                    }
                    bite();
                },
                showBalls: function (balls, callback) {
                    var self = this;
                    var BallsBox = new createjs.Container();
                    var timeFunc = createjs.Ease.quartOut;
                    var ballsShape = new createjs.Shape();
                    var _ballBounds = self.config.ballBounds;
                    var _ballsBounds = self.config.ballsBounds;
                    var _clip = _ballsBounds.clip;

                    BallsBox.regX = _ballsBounds.width / 2;
                    BallsBox.x = cw / 2;
                    BallsBox.y = _ballsBounds.hideStatus.y;
                    BallsBox.scaleX = BallsBox.scaleY = _ballsBounds.hideStatus.scale;
                    BallsBox.alpha = _ballsBounds.hideStatus.alpha;

                    self.GameBox.addChild(BallsBox);
                    self.BallsBox = BallsBox;

                    for (var i = 0; i < balls.length; i++) {
                        var BallItemBox = new createjs.Container();
                        var ballShadowSprite, ballSprite;
                        ballShadowSprite = Tools.createSprite('boxSprite', 'ballShadow');
                        ballShadowSprite.x = ballShadowSprite.y = 5;
                        ballShadowSprite.alpha = 0;
                        ballSprite = Tools.createSprite('boxSprite', 'ball' + balls[i]);

                        BallItemBox.regX = BallItemBox.regY = _ballBounds.width / 2;
                        BallItemBox.x = (i - 1) * 200 + _ballsBounds.width / 2;
                        BallItemBox.addChild(ballShadowSprite);
                        BallItemBox.addChild(ballSprite);
                        BallsBox.addChild(BallItemBox);
                        createjs.Tween.get(BallItemBox, {
                            loop: true
                        }).to({
                            rotation: 360
                        }, _ballBounds.rotateTime);
                    }

                    ballsShape.graphics.drawRect(_clip[0], _clip[1], _clip[2], _clip[3]);
                    BallsBox.mask = ballsShape;

                    createjs.Tween.get(BallsBox).to({
                        alpha: _ballsBounds.showStatus.alpha,
                        y: _ballsBounds.showStatus.y,
                        scaleX: _ballsBounds.showStatus.scale,
                        scaleY: _ballsBounds.showStatus.scale
                    }, _ballsBounds.showTime, timeFunc).call(function () {
                        rotateBall();

                        function rotateBall(i) {
                            if (i >= 3) {
                                return;
                            }
                            if (!i) {
                                i = 0;
                            }
                            createjs.Tween.get(BallsBox.getChildAt(i), {
                                loop: false,
                                override: true
                            }).to({
                                rotation: 360
                            }, _ballBounds.rotateTime, timeFunc).call(function () {
                                showShadow(i);
                                i++;
                                rotateBall(i);
                            });
                        }

                        function showShadow(i) {
                            var shadow = BallsBox.getChildAt(i).getChildAt(0);
                            createjs.Tween.get(shadow, {
                                loop: false,
                                override: true
                            }).to({
                                alpha: 360
                            }, _ballBounds.shadowShowTime, timeFunc);
                        }
                        if (callback && typeof (callback) == 'function') {
                            callback();
                        }
                    });
                },
                hideBalls: function (time, callback) {
                    var self = this;
                    var _ballsBounds = self.config.ballsBounds;
                    if (self.BallsBox === null) {
                        return;
                    }
                    createjs.Tween.get(self.BallsBox).to({
                        alpha: 0,
                    }, time || _ballsBounds.hideTime).call(function () {
                        self.GameBox.removeChild(self.BallsBox);
                        self.BallsBox = null;
                        if (callback && typeof (callback) == 'function') {
                            callback();
                        }
                    });
                },
                initLight: function () {
                    var self = this;
                    var _lightBounds = self.config.lightBounds;
                    var LightBox = new createjs.Container();
                    var light = Tools.createSprite('lightSprite');
                    LightBox.addChild(light);
                    LightBox.regX = _lightBounds.width / 2;
                    LightBox.regY = _lightBounds.height / 2;
                    LightBox.x = cw / 2;
                    LightBox.y = _lightBounds.y;
                    LightBox.alpha = 0;

                    self.LightBox = LightBox;
                    self.GameBox.addChild(LightBox);
                },
                showLight: function () {
                    var self = this;
                    var _lightBounds = self.config.lightBounds;
                    var _scaleRange = _lightBounds.scaleRange;
                    var _alphaRange = _lightBounds.alphaRange;
                    var alpha = _alphaRange[0];
                    var scale = _scaleRange[0];

                    createjs.Tween.get(self.LightBox, {
                        loop: true
                    }).to({
                        rotation: 360
                    }, _lightBounds.rotateTime);


                    blinkLight();

                    function blinkLight() {
                        createjs.Tween.get(self.LightBox).to({
                            alpha: alpha,
                            scaleX: scale,
                            scaleY: scale
                        }, _lightBounds.blinkTime).call(function () {
                            if (alpha == _alphaRange[0]) {
                                alpha = _alphaRange[1];
                            } else {
                                alpha = _alphaRange[0];
                            }
                            if (scale == _scaleRange[0]) {
                                scale = _scaleRange[1];
                            } else {
                                scale = _scaleRange[0];
                            }
                            blinkLight();
                        });
                    }
                },
                hideLight: function () {
                    var self = this;
                    var _lightBounds = self.config.lightBounds;
                    var _scaleRange = _lightBounds.scaleRange;

                    createjs.Tween.get(self.LightBox, {
                        override: true
                    }).to({
                        scale: _scaleRange[0],
                        alpha: 0
                    }, _lightBounds.hideTime).call(function () {
                        /*
                          如果不设置这个, 当光圈正好转动到360deg
                          下次再次显示light时候(360deg --> 360deg)
                          light 就不会再转动
                        */
                        self.LightBox.rotation = 0;
                    });
                },
                initEye: function () {
                    var self = this;
                    var DragonEye = new createjs.Container();
                    var dragonHeadEyeLeft = Tools.createSprite('boxSprite', 'dragonEyeLeft');
                    var _dragonEyeBounds = self.config.dragonEyeBounds;
                    var _dragonEyeLeftBounds = _dragonEyeBounds.leftBounds;
                    var _dragonEyeRightBounds = _dragonEyeBounds.rightBounds;
                    self.DragonEye = DragonEye;
                    // dragonHeadLeft.x = self.config.boxTopBeginPos.x
                    // dragonHeadLeft.y = self.config.boxTopBeginPos.y
                    dragonHeadEyeLeft.x = _dragonEyeLeftBounds.x;
                    dragonHeadEyeLeft.y = _dragonEyeLeftBounds.y;
                    self.dragonHeadEyeLeft = dragonHeadEyeLeft;

                    var dragonHeadEyeRight = Tools.createSprite('boxSprite', 'dragonEyeRight');
                    dragonHeadEyeRight.x = _dragonEyeRightBounds.x;
                    dragonHeadEyeRight.y = _dragonEyeRightBounds.y;
                    self.dragonHeadEyeLeft = dragonHeadEyeLeft;

                    DragonEye.addChild(dragonHeadEyeLeft);
                    DragonEye.addChild(dragonHeadEyeRight);
                    self.DragonHead.addChild(DragonEye);
                },
                blinkEye: function (time) {
                    var self = this;
                    var alpha = 0;
                    var timeFunc = createjs.Ease.quartOut;
                    var _dragonEyeBounds = self.config.dragonEyeBounds;
                    var _dragonEyeStatus = _dragonEyeBounds.status;

                    _dragonEyeStatus = 'blink';

                    function blink() {
                        if (_dragonEyeStatus != 'blink') {
                            return;
                        }
                        createjs.Tween.get(self.DragonEye, {
                            override: true
                        }).to({
                            alpha: alpha
                        }, time || _dragonEyeBounds.blinkTime, createjs.Ease.quartOut).call(function () {
                            if (alpha === 0) {
                                alpha = 1;
                            } else {
                                alpha = 0;
                            }
                            if (timeFunc == createjs.Ease.quartOut) {
                                timeFunc = createjs.Ease.quartIn;
                            } else {
                                timeFunc = createjs.Ease.quartOut;
                            }
                            blink();
                        });
                    }
                    blink();
                },
                stopBlinkEye: function (time) {
                    var self = this;
                    var _dragonEyeBounds = self.config.dragonEyeBounds;
                    var _dragonEyeStatus = _dragonEyeBounds.status;

                    _dragonEyeStatus = 'normal';
                    createjs.Tween.get(self.DragonEye, {
                        override: true
                    }).to({
                        alpha: 0
                    }, time || _dragonEyeBounds.hideTime, createjs.Ease.quartOut);
                },
                initFire: function () {
                    // 龙在呼吸的时候吐火的效果 暂时做不到
                    var self = this;
                },
                initConfig: function () {
                    var self = this;
                    self.config = {
                        gameBoxBounds: {
                            y: 117
                        },
                        dragonMouse: {
                            range: [200, 220],
                            status: 'close',
                            biteTime: 500,
                            biteWaiteTime: 300,
                            closeTime: 300,
                            openTime: 300,
                        },
                        dragonEyeStatus: 'normal', // blink normal
                        dragonHeadBounds: {
                            width: 424,
                            height: 384,
                            hideStatus: {
                                scale: 0,
                                alpha: 0
                            },
                            showStatus: {
                                scale: 1,
                                alpha: 1
                            },
                            showTime: 700,
                            topBounds: {
                                width: 360,
                                height: 384,
                                x: 10,
                                y: 0
                            },
                            bottomBounds: {
                                width: 424,
                                height: 276,
                                y: 200,
                                x: 0
                            }
                        },
                        dragonEyeBounds: {
                            leftBounds: {
                                width: 40,
                                height: 35,
                                x: 157,
                                y: 193
                            },
                            rightBounds: {
                                width: 40,
                                height: 35,
                                x: 229,
                                y: 193
                            },
                            blinkTime: 300,
                            hideTime: 300
                        },
                        lightBounds: {
                            width: 580,
                            height: 591,
                            y: 200,
                            scaleRange: [1, 1.2],
                            alphaRange: [0.5, 0.8],
                            hideTime: 300,
                            blinkTime: 2000,
                            rotateTime: 20000
                        },
                        ballBounds: {
                            width: 149,
                            height: 149,
                            space: 200,
                            hideTime: 300,
                            shadowShowTime: 300,
                            rotateTime: 250
                        },
                        ballsBounds: {
                            width: 522,
                            height: 174,
                            hideStatus: {
                                scale: 0.1,
                                alpha: 0.3,
                                y: 280
                            },
                            showStatus: {
                                scale: 1,
                                alpha: 1,
                                y: 490
                            },
                            clip: [-50, 300, 700, 290],
                            showTime: 1300
                        },
                        maxBoxTopMove: -300,
                        boxRotation: {
                            range: 4,
                            direction: 1, // 1 顺时针 -1 逆时针
                        }
                    };
                }
            };
            var Dragon = new createDragon();
            var Game = {
                init: function () {
                    var self = this;
                    self.setStatus('end');
                    Dragon.init();
                },
                start: function () {
                    var self = this;
                    if (self.status !== 'end') {
                        return;
                    }
                    self.setStatus('start');
                    Dragon.showLight();
                    Dragon.bite();
                    Dragon.blinkEye();
                },
                play: function (resultArr, showWinSign, resetGame) {
                    var self = this;
                    if (self.status !== 'start') {
                        return;
                    }
                    self.setStatus('play');
                    Dragon.openMouth('', function () {
                        Dragon.stopBlinkEye();
                        Dragon.showBalls(resultArr);
                    });
                    setTimeout(function () {
                        Dragon.hideBalls('', function () {
                            showWinSign();
                        });
                    }, 3000);
                    setTimeout(function () {
                        Dragon.hideBalls();
                        self.end(resetGame);
                    }, 5000);
                },
                cancel: function (resetGame) {
                    var self = this;

                    if (self.status === 'end') {
                        return;
                    }

                    Dragon.hideLight();
                    Dragon.stopBlinkEye();
                    Dragon.closeMouth('', function () {
                        self.setStatus('end');
                        resetGame();
                    });
                },
                end: function (resetGame) {
                    var self = this;
                    Dragon.hideLight();
                    Dragon.hideBalls();
                    Dragon.stopBlinkEye();
                    Dragon.closeMouth('', function () {
                        self.setStatus('end');
                        resetGame();
                    });
                },
                getStatus: function () {
                    var self = this;
                    return self.status;
                },
                setStatus: function (status) {
                    var self = this;
                    self.status = status;
                },
            };
            _this.Game = Game;
            Game.init();

        },
        /**
         * 重置游戏
         */
        restGame: function () {
            var self = this;

            self.restParam();

            self.Model.prizeAmount = null;
            self.Model.payback = { code: null, betPoint: null, paybackPoint: null };
        },
        restParam: function () {
            var self = this;

            self.Model.gamestart = false;
            self.Model.resultready = false;

            $('#gsCtrl').children('a.active').removeClass('active');
        },
        hideWiningSign: function () {
            var self = this;
            self.View.$winTxtCont.hide();
            self.View.$loseTxtCont.hide();
            if (self.win) {
                self.win.visible = false;
                self.lose.visible = false;
            }
        },
        drawSource: function (source) {
            this[source] = new createjs.Bitmap(this.res.txtSprite.image);
            this[source].sourceRect = this.res.txtSprite[source];
            this[source].name = source;
        },
        /**
         * 赢牌，输
         */
        drawWiningSign: function () {
            var self = this;
            var winpos = { x: 35, y: 380 };
            var losepos = { x: 35, y: 430 };

            self.Model.isLose = null;
            if (!self.win) {
                self.drawSource('win');
                self.drawSource('lose');

                self.win.visible = false;///*self.textWinCont.visible =*/
                self.win.y = winpos.y;
                self.win.x = winpos.x;
                this.stage.addChild(self.win);

                self.lose.visible = false;/*self.textLoseCont.visible =*/
                self.lose.y = losepos.y;
                self.lose.x = losepos.x;
                this.stage.addChild(self.lose);

            }

            var _donetype = 0;
            if (self.Model.prizeAmount || self.Model.prizeAmount == 0) {
                if (self.Model.prizeAmount > 0) {//win
                    _donetype = 2;
                    if (1 == self.Model.prizeType || 2 == self.Model.prizeType) {
                        _donetype = 3;//如果奖品是万里通积分,游戏分
                    }
                } else {
                    _donetype = 1;//lose
                }
            }
            var _restime = 10;
            switch (_donetype) {
                case 0:
                    // self.userAccount();
                    break;
                case 1://lose

                    self.data.audiolose.play();
                    self.lose.visible = true;
                    self.Model.isLose = true;

                    self.View.$loseTxtCont.show();
                    if (!self.Model.payback) {
                        self.socketExec();
                    }
                    self.settleScore(0);
                    _restime = 300;
                    break;
                case 3: //win
                case 2:
                    var n = (self.Model.boult[0] + '、' + self.Model.boult[1] + '、' + self.Model.boult[2]).toString();
                    var s = self.Model.guesstype.toUpperCase();

                    switch (s) {
                        case 'SAME':
                            s = '合';
                            break;
                        case 'LARGE':
                            s = '天';
                            break;
                        case 'SMALL':
                            s = '地';
                            break;
                    }
                    self.data.audiowin.play();

                    self.View.$winTxtCont.find('.boult').html(n);
                    self.View.$winTxtCont.find('.type').html(s);
                    self.View.$winTxtCont.find('.points').html(self.Model.prizeAmount);

                    self.View.$winTxtCont.show();
                    self.data.audiowin.play();
                    self.win.visible = true;

                    self.win.scaleX = self.win.scaleY = 8;
                    self.win.x = self.win.y = -800;
                    createjs.Tween.get(self.win, { loop: false }).to({ scaleX: 1, scaleY: 1, x: winpos.x, y: winpos.y }, 150, createjs.Ease.sineInOut());
                    $(".GS").animate("roll", { duration: 50, easing: 'ease-in-out' });//震
                    self.settleScore(self.Model.prizeAmount);
                    _restime = 300;
                    break;
                default:
                    ;
            }
        },
        /**
         * score结算，兑奖
        */
        settleScore: function (pr) {
            var self = this;

            if (self.Model.tCoin >= self.Model.bet) {
                self.Model.tCoin -= self.Model.bet;
                self.Model.gameScore += pr;
            } else if (self.Model.gameScore >= self.Model.bet) {
                self.Model.gameScore = self.Model.gameScore - self.Model.bet + pr;
            } else {
                self.userAccount();
            }

            self.Model.prizeAmountTotal += pr;
            $('div.purse span.purse-T span').html(self.Model.tCoin);
            $('div.purse span.purse-R span').html(self.Model.gameScore);
            self.setIncoming();
            if (self.Model.payback) {
                // var LB_paInsure = new LightboxV2({ target: $("#paInsure") }).hookHidden(function (){
                //   self.socketExec();
                // });
                $('#paInsure .cont span').html(self.Model.payback.paybackPoint);
                self.View.LB_paInsure.show().hideDelay(20000);
            }
        },
        /**
         * tips,poup
         */
        popbox: function (msg, title, btntxt) {
            var self = this;
            var $tip = $('#tips');
            $tip.find('.cont').html(msg);
            if (title) {
                $tip.find('h2').html(title);
            }
            self.View.LB_tips.show();
        },
        /**
         * 异常
         */
        queryExcep: function (code, msg) {
            var self = this;
            self.data.torecharge = false;
            msg = msg || '';
            code = parseInt(code);
            switch (code) {
                case 0:
                    return true;
                    break;
                case 1000:
                    msg = '没有相关记录';
                    break;
                case 1001:
                    msg = '扣除游戏币失败';
                    break;
                case 1002:
                    msg = '投币失败';
                    break;
                case 81:
                    location.href = "/?act=otp&st=otpPage";
                    break;
                case 1:
                    msg = '您的网络不稳定，请检查网络后重试！';
                    break;
                case 10:
                    window.location.href = '?act=user&st=login';
                    break;
                case 100:
                case 103:
                    self.Model.checkLogin = false;
                    if (self.Model.gamestart) {
                        msg = '亲，登陆后才可以游戏哦';
                    }
                    break;
                case 3:
                    msg = '不在可游戏时间段哦';
                    break;
                case 4:
                    msg = '亲，您今天已经赢爆了！产品经理已经拔剑自刎了，请给小伙伴们一条生路吧。';
                    break;
                case 5:
                    msg = '亲，余额不够了';
                    self.data.torecharge = true;
                    break;
                case 50:
                    msg = '万里通单笔消费达上限';
                    break;
                case 51:
                    msg = '您的积分或欢乐值超过当日最大使用额度!适度游戏益脑 沉迷游戏伤身 明天再继续吧';
                    break;
                default:
                    if (self.Model.gamestart) msg = '龙被叫烦了，请稍后再试！';
                    else msg = '网络出错啦！'
            }

            if (msg && 　msg.length > 0) {
                if (!self.Model.gamestart) {
                    self.popbox(msg);
                    self.data.msg = '';
                } else {
                    self.data.msg = msg;
                }
            }
            return false
        },
        /**
         * 用户收益
         */
        setIncoming: function () {//1029
            var self = this;
            var $profit = $('#indicate .profit');
            var _poolString = number2html(self.Model.prizeAmountTotal);
            $profit.html(_poolString);

            function number2html(number) {
                if (!number) { number = 0; }
                number = String(number);
                var stringNumber = [];
                var n = 0;
                for (var i = number.length - 1; i >= 0; i--) {
                    stringNumber.push('<i class="pn' + number.charAt(i) + '"></i>');
                    n++;
                }
                stringNumber.reverse();
                return stringNumber.join("");
            }
        },
        /**
        * 账户信息
        */
        userAccount: function (callback) {
            if (!GM.userLogged) { return; }
            var self = this;
            $.ajax({
                type: "get",
                url: "?act=game_gamebase&st=queryUserAccount&Type=1&gameId=" + GM.gameId,//?act=guesswap&st=queryUserAccount
                success: function (d) {
                    var rsp = typeof d === 'string' ? $.parseJSON(d) : d;
                    // if(!self.queryExcep(rsp.statusCode)){
                    //   return false;
                    // }

                    self.Model.gameScore = rsp.gameScore;
                    self.Model.tCoin = rsp.TCoin;
                    self.Model.total = rsp.total;

                    $('div.purse span.purse-T span').html(self.Model.tCoin);
                    $('div.purse span.purse-R span').html(self.Model.gameScore);

                    var inpVal = Math.ceil(rsp.total / 10000) * 100;
                    inpVal = inpVal > 10000 ? 10000 : inpVal;
                    inpVal = inpVal < 100 ? 100 : inpVal;
                    self.Model.defaultScore = inpVal;

                    if (!self.Model.userNoticed) {
                        $('#betCtrl input[type="tel"]').val(self.Model.defaultScore);
                        if (self.Model.progressSts) {
                            self.popbox('你当前的默认投币额是' + self.Model.defaultScore);
                            self.Model.userNoticed = true;
                        } else {
                            setTimeout(function () {
                                self.popbox('你当前的默认投币额是' + self.Model.defaultScore);
                                self.Model.userNoticed = true;
                            }, 500)
                        }

                    }

                    setTimeout(function () {
                        self.View.LB_tips.hide();
                    }, 2000);
                    betChoose(self.Model.total);

                    if (typeof callback === 'function') {
                        callback()
                    }
                }
            });

            function betChoose(total) {
                var ranks = [];
                if (total <= 100000) {
                    ranks = [
                        { 'map': '100', 'value': 100 },
                        { 'map': '200', 'value': 200 },
                        { 'map': '500', 'value': 500 },
                        { 'map': '1000', 'value': 1000 },
                        { 'map': '2000', 'value': 2000 }
                    ];
                } else if (total < 1000000) {
                    ranks = [
                        { 'map': '200', 'value': 200 },
                        { 'map': '500', 'value': 500 },
                        { 'map': '1000', 'value': 1000 },
                        { 'map': '2000', 'value': 2000 },
                        { 'map': '5000', 'value': 5000 }
                    ];
                } else if (total < 10000000) {
                    ranks = [
                        { 'map': '1000', 'value': 1000 },
                        { 'map': '2000', 'value': 2000 },
                        { 'map': '5000', 'value': 5000 },
                        { 'map': '1W', 'value': 10000 },
                        { 'map': '2W', 'value': 20000 }
                    ];
                } else {
                    ranks = [
                        { 'map': '1000', 'value': 1000 },
                        { 'map': '5000', 'value': 5000 },
                        { 'map': '1W', 'value': 10000 },
                        { 'map': '5W', 'value': 50000 },
                        { 'map': '10W', 'value': 100000 }
                    ];
                }
                var _html = '';
                for (var i = 0, l = ranks.length; i < l; i++) {
                    _html += '<li data-value="' + ranks[i]['value'] + '">' + ranks[i]['map'] + '</li>'
                }
                $('#betCtrl ul').html(_html);
            }
        },
        /**
        * 跑马灯
        */
        getAnnounce: function () {
            $.ajax({
                type: "get",
                url: "?act=game_rolldice2&st=get_marguee",//?act=guesswap&st=getAnnounce
                success: function (d) {
                    var rsp = typeof d === 'string' ? $.parseJSON(d) : d;
                    var str = '';
                    // for(var type in rsp){
                    if (!rsp.list || rsp.list.length < 1) {
                        throw (new Error('跑马灯接口异常'));
                        return
                    }
                    $.each(rsp.list, function (i, k) {
                        // for(var k in rsp[type]){
                        str += "<li>";
                        if (k.rank == 1) {
                            str += "<i class='" + "jin'><\/i>";
                        } else if (k.rank == 2) {
                            str += "<i class='" + "tong'><\/i>";
                        } else if (k.rank == 3) {
                            str += "<i class='" + "yin\'><\/i>";
                        }
                        if (k['type'] == 'dice') {
                            str += "<span>" + k['disName'] + "<\/span>正在打杀，大家赶紧来膜拜吧、";
                        } else {
                            if (k['type'] == 'payback') {
                                str += "<span style=\"color:red\">" + k['disName'] + "使用平安娱乐险,免除" + k['prize_amount'] + "损失<\/span>、";
                            } else {
                                str += "恭喜<span>" + k['disName'] + "<\/span>猜中豹子获得<span>" + k['prize_amount'] + "<\/span>、 ";
                            }
                        }
                        str += "<\/li>";
                        // }
                        // }
                    });
                    $('.top-new ul').html(str);
                }
            });
        },
        checkLogin: function (callback) {
            var self = this;
            $.ajax({
                type: "get",
                url: "?act=game_rolldice2&st=query_login_status",//?act=guesswap&st=check_login&goGuessWap=1
                success: function (d) {
                    var res = typeof d === 'string' ? $.parseJSON(d) : d;
                    if (res.statusCode == '0000') {
                        self.Model.checkLogin = true;
                    }
                    if (typeof callback === 'function') {
                        callback()
                    }
                }
            });
        },
        /**
         *
         */
        play: function (type) {
            var self = this;
            self.Model.gamestart = true;
            if (!self.Model.checkLogin) {
                setTimeout(function () {
                    location.href = self.Conf.loginUrl;
                }, 0);
                return
            }
            var $val = $('#betCtrl input[type="tel"]');
            var msg = checkBetVal($val.val());
            if (msg.length > 0) {
                self.restParam();
                self.popbox(msg);
                return
            }
            var bet = $val.val();
            self.Model.bet = bet;
            self.loadguess(type, bet);

            function checkBetVal(_val) {
                var tipBetStr = '';
                if (!/^\d*$/.test(_val)) {
                    tipBetStr = '投币金额必须是正整数';
                } else if (_val == 0) {
                    tipBetStr = '还木有投币，赶快投币再来点我吧！';
                } else if (_val < 100) {
                    tipBetStr = '最小投币额为100';
                } else if (_val <= 10000) {
                    if (_val % 100 !== 0) {
                        tipBetStr = '投币额在100-10000之间,请输入100的整数倍';
                    }
                } else if (_val <= 100000) {
                    if (_val % 5000 !== 0) {
                        tipBetStr = '投币额在10000-100000之间,请输入5000的整数倍';
                    }
                } else if (_val <= 500000) {
                    if (_val % 10000 !== 0) {
                        tipBetStr = '投币额在100000-500000之间,请输入10000的整数倍';
                    }
                } else if (_val > 500000) {
                    tipBetStr = '最大投币额为500000';
                }
                return tipBetStr;
            }
        },
        /**
         * play guess 请求
         */
        loadguess: function (type, bet) {
            var self = this;
            var _timestamp0 = new Date().getTime();
            $.ajax({
                type: "get",
                url: "?act=game_rolldice2&st=play",
                data: { amount: bet, type: type },
                timeout: 15000,
                success: function (d) {
                    var _timestamp1 = new Date().getTime();
                    var rsp = typeof d === 'string' ? $.parseJSON(d) : d;
                    var _intel = _timestamp1 - _timestamp0;
                    // 防沉迷
                    if (GM.addict && GM.addict(rsp)) {
                        _stopshake(_intel);
                        return false
                    }
                    if (!self.queryExcep(rsp.statusCode)) {
                        self.data.errorcode = true;
                        if (window.GM && GM.getUserAccount) {
                            GM.getUserAccount(function (d) {
                                self.Model.gameScore = d.gameScore;
                                self.Model.tCoin = d.TCoin;
                            });
                        } else {
                            self.userAccount();
                        }
                        _stopshake(_intel);
                        return false
                    }

                    self.Model.guesstype = rsp.type;
                    self.Model.boult = rsp.value;
                    self.Model.prizeAmount = rsp.prizeAmount;
                    self.Model.rechargeType = rsp.rechargeType;
                    self.Model.prizeType = rsp.prizeType;
                    // self.Model.gameCoin = rsp.gameCoin;
                    // self.Model.daoju = rsp.daoju;
                    self.Model.payback = rsp.payback || null;

                    self.Model.userId = rsp.userId;
                    self.Model.resultready = true;

                    if (self.Model.prizeAmount || self.Model.prizeAmount == 0) {
                        if (self.Model.prizeAmount > 0) {//win
                            self.Model.resultType = 'win';
                        } else {
                            self.Model.resultType = 'lose';
                        }
                    }
                    self.data.audioBallShow.play();
                    self.Game.play(self.Model.boult, function () {
                        // 显示输赢信息
                        self.drawWiningSign();
                    }, function () {
                        // 关闭重置所有
                        self.hideWiningSign();
                        self.restGame();
                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    self.data.errorcode = true;
                    self.userAccount();
                    var _timestamp1 = new Date().getTime();
                    var _intel = _timestamp1 - _timestamp0;
                    _stopshake(_intel);
                    self.restGame();
                    if (textStatus == "timeout") {
                        self.popbox(MSG.timeout);
                    } else {
                        self.popbox('哎~网络出错啦！');
                    }
                }
            });

            function _stopshake(t) {
                var stopIt = function () {
                    if (t >= 2000) {
                        self.Game.cancel(function () {
                            self.restGame();
                        });
                    } else {
                        setTimeout(function () {
                            self.Game.cancel(function () {
                                self.restGame();
                            });
                        }, (2000 - t));
                    }
                }
                stopIt();

            }
        },
        /**
        * 充值, 关闭弹窗
        */
        redirectPay: function (m) {
            var self = this;
            var value = m;

            var currentUrl = GM.payPar.redirect_uri;
            var gameId = GM.payPar.gameId;
            var gameName = GM.payPar.tradeName;
            var shuoldPay = value;
            var platform = GM.payPar.platform;
            window.location.href = '/?act=payment&gameId=' + gameId + '&tradeName=' + gameName + '&amount=' + shuoldPay + '&platform=' + platform + '&redirect_uri=' + currentUrl;

            /*
            $.post('?act=guess&st=get_changed_amount', {amount:value}, function(msg){
                if (0 == msg.code) {
                    window.location.href = '?act=payment&gameId='+GM.gameInfo.gameId+'&tradeName='+ GM.gameInfo.gameName +'&amount='+msg.shuoldPay;
                } else {
                    self.popbox(msg.msg);
                }
            }, 'json');*/
        },
        /**
         * 音效
         */
        audioCreat: function () {
            var _self = this;
            var $body = $('body');
            var $audio = $('<audio></audio>');
            var $sourceMpeg = $('<source type="audio/mpeg" />');
            var $sourceOgg = $('<source type="audio/ogg" />');
            var $sourceWav = $('<source type="audio/wav" />');
            return function (para) {
                var isInit = false;
                var $el;
                var init = function () {
                    if (isInit) {
                        return;
                    }
                    isInit = true;
                    $el = $audio.clone().hide().css({
                        position: 'absolute',
                        width: 0,
                        height: 0,
                        left: 0,
                        bottom: 0
                    });
                    var mpeg = para.mpeg;
                    var ogg = para.ogg;
                    var wav = para.wav;
                    var attr = para.attr;
                    if (attr) {
                        for (var j in attr) {
                            $el.attr(j, attr[j]);
                        }
                    }
                    if (mpeg) {
                        $sourceMpeg.clone().attr('src', mpeg.src).appendTo($el);
                    }
                    if (ogg) {
                        $sourceOgg.clone().attr('src', ogg.src).appendTo($el);
                    }
                    if (wav) {
                        $sourceWav.clone().attr('src', wav.src).appendTo($el);
                    }
                    $el.appendTo($body);
                }
                return {
                    waitTime: 150,
                    init: function () {
                        try {
                            init();
                            return this;
                        } catch (e) { console.log(e) }
                    },
                    start: function () {
                        try {
                            if ($('#indicate .icon-voice').hasClass("horn-forb")) {
                                return;
                            }
                            this.init();
                            this.load().play();
                        } catch (e) {
                            console.log(e)
                        }
                    },
                    play: function () {
                        this.init();
                        this.pause();
                        /*setTimeout(function() {
                          if ($el[0].play) {
                            $el[0].play();
                          }
                        }, this.waitTime);*/
                        if ($el[0].play) {
                            $el[0].play();
                        }
                        return this;
                    },
                    pause: function () {
                        try {
                            this.init();
                            if ($el[0].pause) {
                                $el[0].pause();
                            }
                            return this;
                        } catch (e) { console.log(e) }
                    },
                    load: function () {
                        this.init();
                        if ($el[0].load) {
                            $el[0].load();
                        }
                        return this;
                    }
                }
            }
        }(),
        /**
         *
         */
        audioInit: function () {
            var _self = this;
            var imgPath = _self.Conf.audioPath;
            //背景
            _self.data.audiobg = _self.audioCreat({
                mpeg: {
                    src: imgPath + 'bgmusic.mp3'
                },
                attr: {
                    loop: 'loop'
                }
            });
            //按钮
            _self.data.audiobtn = _self.audioCreat({
                mpeg: {
                    src: imgPath + 'btnSound.mp3'
                }
            });
            //click
            _self.data.audioclick = _self.audioCreat({
                mpeg: {
                    src: imgPath + 'click.mp3'
                }
            });
            //赢了
            _self.data.audiowin = _self.audioCreat({
                mpeg: {
                    src: imgPath + 'winSound.mp3'
                }
            });
            //输了
            _self.data.audiolose = _self.audioCreat({
                mpeg: {
                    src: imgPath + 'failSound.wav'
                }
            });
            //胜利
            _self.data.audioleoSound = _self.audioCreat({
                mpeg: {
                    src: imgPath + 'leoSound.wav'
                }
            });
            //球出现
            _self.data.audioBallShow = _self.audioCreat({
                mpeg: {
                    src: imgPath + 'dragonballs/ballshow.mp3'
                }
            });

            _self.data.audiobg.init();
            _self.data.audiobtn.init();
            _self.data.audioclick.init();
            _self.data.audiowin.init();
            _self.data.audiolose.init();
            _self.data.audioleoSound.init();

            _self.data.audioBallShow.init().load().play().pause();
        }
    };

}(Zepto, window);
/**
 *
 */
$(function () {
    progressbar(50, 0.3);
    Guess.init();
})
